<template>
  <view class="container">
    <view class="content">
      <!-- 文章列表 -->
      <view class="article-list">
        <view 
          v-for="(item, index) in articleList" 
          :key="index" 
          class="article-item"
          @click="viewArticleDetail(item)"
        >
          <image 
            :src="processImageUrl(item.coverImage || defaultCover)" 
            class="article-cover" 
            mode="aspectFill"
            @error="handleImageError(index)"
          ></image>
          <view class="article-content">
            <text class="article-title">{{ item.title || item.articleTitle || '无标题' }}</text>
            <view class="article-meta">
              <view class="meta-left">
                <text class="category">{{ item.category || item.articleCategory || '健康知识' }}</text>
                <text class="publish-time">{{ formatDate(item.publishTime || item.createTime || item.updatedAt) }}</text>
              </view>
              <text class="read-count">{{ formatReadCount(item.viewCount || item.readCount || item.views || 0) }}阅读</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="loading-more" v-if="loading">
        <view class="loading-content">
          <text class="loading-text">加载中...</text>
        </view>
      </view>
      <view class="no-more" v-if="!hasMore && articleList.length > 0">
        <view class="no-more-content">
          <text class="no-more-text">没有更多数据了</text>
        </view>
      </view>
      <view class="empty" v-if="!loading && articleList.length === 0">
        <text class="empty-text">暂无文章</text>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view class="tab-item" @click="handleTabClick('home')">
        <text class="tab-icon">🏠</text>
        <text class="tab-text">首页</text>
      </view>
      <view class="tab-item" @click="handleTabClick('survey')">
        <text class="tab-icon">📋</text>
        <text class="tab-text">问卷</text>
      </view>
      <view class="tab-item" @click="handleTabClick('record')">
        <text class="tab-icon">✅</text>
        <text class="tab-text">记录</text>
      </view>
      <view class="tab-item active" @click="handleTabClick('knowledge')">
        <text class="tab-icon" style="color: #2979ff;">📚</text>
        <text class="tab-text" style="color: #2979ff;">知识</text>
      </view>
      <view class="tab-item" @click="handleTabClick('my')">
        <text class="tab-icon">👤</text>
        <text class="tab-text">我的</text>
      </view>
    </view>
  </view>
</template>

<script>
// 路径用相对路径，兼容各种构建环境
import articleApi from '../../api/article';
import mixin from '../../utils/mixin';

export default {
  name: 'KnowledgePage',
  mixins: [mixin],
  data() {
    return {
      articleList: [],
      loading: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 10,
      defaultCover: 'http://localhost:9001/image/article/67fce526-83ba-49ef-9d14-86ab9a803a2b.png'
    };
  },
  // 兼容H5和小程序，两个生命周期都调用一次
  created() {
    console.log('知识页面 - created生命周期被调用');
    this.getArticleList(true);
  },
  onLoad(options) {
    // 兜底处理，防止 options 为 null 或 undefined
    options = options || {};
    // 不要给 this.query 或 this.$route.query 赋值，直接用 options
    console.log('知识页面 - onLoad生命周期被调用', options);
    this.getArticleList(true);
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getArticleList(true);
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.getArticleList(false);
    }
  },
  methods: {
    formatReadCount(count) {
      if (!count) return '0';
      count = Number(count);
      if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'k';
      }
      return count.toString();
    },
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      // 兼容iOS日期格式
      const safeStr = dateStr.replace(/-/g, '/');
      const date = new Date(safeStr);
      const now = new Date();
      if (isNaN(date.getTime())) return '未知时间';
      const diff = (now - date) / 1000;
      if (diff < 60) {
        return '刚刚';
      } else if (diff < 3600) {
        return Math.floor(diff / 60) + '分钟前';
      } else if (diff < 86400) {
        return Math.floor(diff / 3600) + '小时前';
      } else if (diff < 2592000) {
        return Math.floor(diff / 86400) + '天前';
      } else {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    },
    async getArticleList(refresh = false) {
      console.log('getArticleList called, refresh:', refresh);
      if (this.loading) return;
      try {
        this.loading = true;
        if (refresh) {
          this.currentPage = 1;
          this.articleList = [];
          this.hasMore = true;
        }
        
        console.log('准备请求后端articlecontroller接口', this.currentPage, this.pageSize);
        const res = await articleApi.getArticleList(this.currentPage, this.pageSize);
        console.log('后端articlecontroller返回数据:', res);
        console.log(res);
        // 适配后端返回的数据结构
        if (res && res.code === 1 && res.data) {
          // 根据后端数据结构，文章列表在res.data.list中
          let articles = [];
          let total = 0;
          
          if (res.data.list && Array.isArray(res.data.list)) {
            // 如果data包含list字段
            articles = res.data.list;
            total = res.data.total || articles.length;
          } else if (Array.isArray(res.data)) {
            // 如果data直接是数组
            articles = res.data;
            total = res.total || articles.length;
          } else if (res.data.articles && Array.isArray(res.data.articles)) {
            // 如果data包含articles字段
            articles = res.data.articles;
            total = res.data.total || articles.length;
          }

          // 字段映射，兼容后端下划线命名
          articles = articles.map(item => {
            let cover = item.coverImage || item.cover_image || '';
            if (cover && !/^https?:\/\//.test(cover)) {
              // 如果不是http开头，补全为完整的服务器URL
              if (!cover.startsWith('/image')) {
                cover = '/image' + cover.replace(/^\/static/, '');
              }
              // 添加完整的服务器地址
              cover = 'http://localhost:9001' + cover;
            }
            return {
              ...item,
              coverImage: cover,
              title: item.title || item.articleTitle,
              publishTime: item.publishTime || item.publish_time || item.createTime || item.updatedAt,
              viewCount: item.viewCount || item.readCount || item.views || 0,
              category: item.category || item.articleCategory || '',
              tags: item.tags || item.tagList || []
            };
          });

          console.log('解析后的文章数据:', articles, '总数:', total);
          
          if (refresh) {
            this.articleList = articles;
            console.log('页面数据：', this.articleList);
          } else {
            this.articleList = [...this.articleList, ...articles];
            console.log('页面数据：', this.articleList);
          }
          
          this.hasMore = this.articleList.length < total;
          if (articles.length > 0) this.currentPage++;
        } else {
          console.error('API返回错误:', res);
          if (refresh) {
            this.articleList = [];
          }
          uni.showToast({ 
            title: res?.msg || '获取文章列表失败', 
            icon: 'none',
            duration: 2000
          });
        }
      } catch (e) {
        console.error('请求文章列表失败', e);
        if (refresh) {
          this.articleList = [];
        }
        uni.showToast({ 
          title: '网络连接失败，请检查网络设置', 
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },
    viewArticleDetail(item) {
      uni.navigateTo({
        url: `/pages/knowledge/detail?id=${item.id}`
      });
    },
    handleImageError(index) {
      this.articleList[index].coverImage = this.defaultCover;
    },
    handleTabClick(tab) {
      switch (tab) {
        case 'home':
          uni.navigateTo({ url: '/pages/index/index' });
          break;
        case 'survey':
          uni.navigateTo({ url: '/pages/survey/index' });
          break;
        case 'record':
          uni.navigateTo({ url: '/pages/record/index' });
          break;
        case 'knowledge':
          break;
        case 'my':
          uni.navigateTo({ url: '/pages/my/index' });
          break;
      }
    }
  }
};
</script>

<style>
page {
  height: 100%;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}
.content {
  flex: 1;
  overflow: auto;
  padding: 20rpx;
}
.article-list {
  padding: 20rpx;
  padding-bottom: 120rpx;
}
.article-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.08);
}
.article-cover {
  width: 100%;
  height: 320rpx;
  background-color: #f5f5f5;
}
.article-content {
  padding: 24rpx;
}
.article-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}
.meta-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.category {
  color: #2979ff;
  font-size: 24rpx;
  background-color: rgba(41, 121, 255, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}
.read-count {
  color: #999;
}
.loading-more,
.no-more,
.empty {
  display: flex;
  justify-content: center;
  padding: 30rpx 0;
}

.loading-content,
.no-more-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-text,
.no-more-text {
  color: #999;
  font-size: 26rpx;
}
.empty-text {
  color: #999;
  font-size: 14px;
}

.tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
  background-color: #fff;
  border-top: 1px solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10rpx 0;
}

.tab-icon {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 8rpx;
  line-height: 1;
}

.tab-text {
  font-size: 20rpx;
  color: #666;
  line-height: 1;
}

.tab-item.active .tab-text {
  color: #2979ff;
}

</style> 